package com.ruoyi.iot.hikvision.ys;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.OkHttpUtils;
import com.ruoyi.iot.domain.IotServiceConfig;
import com.ruoyi.iot.service.IIotServiceConfigService;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

///https://open.ys7.com/doc/zh/book/index/device_option.html#device_option-api1
@Service
public class YsTokenService {
    public static final String ys_token_key = "yingshi_token_cache_7_days";
    public static final int token_expire = 60*60*24*7;

    @Autowired
    private IIotServiceConfigService iotServiceConfigService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private YsConfig ysConfig;

    /**
     * 获取萤石token
     * http://open.ys7.com/doc/zh/book/index/user.html
     * @return
     */
    public synchronized String getAccessToken(){
        String redisToken = redisCache.getCacheObject(ys_token_key);
        if(!StringUtils.isEmpty(redisToken)){
            return redisToken;
        }
        final String[] token = {""};
        HashMap<String,String> body = new HashMap<>();
        body.put("appKey",ysConfig.getAppKey());
        body.put("appSecret",ysConfig.getAppSecret());
        OkHttpUtils.getInstance().init()
        .url("https://open.ys7.com/api/lapp/token/get")
        .formBodyPost(body)
        .exec(new OkHttpUtils.OnResponse() {
            @Override
            public void onSuccess(Response response) {
                try {
                    String body = response.body().string();
                    if(!StringUtils.isEmpty(body)){
                        YsTokenResponse ysTokenResponse = JSONObject.parseObject(body,YsTokenResponse.class);
                        if(ysTokenResponse!=null&&ysTokenResponse.data!=null){
                            String ysToken = ysTokenResponse.getData().getString("accessToken");
                            token[0] = ysToken;
                            redisCache.setCacheObject(ys_token_key,ysToken,
                                    token_expire, TimeUnit.SECONDS);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Exception e) {
            }
        });
        return token[0];
    }

    /**
     * {
     *     "data": {
     *         "accessToken": "at.7jrcjmna8qnqg8d3dgnzs87m4v2dme3l-32enpqgusd-1jvdfe4-uxo15ik0s",
     *         "expireTime": 1470810222045
     *     },
     *     "code": "200",
     *     "msg": "操作成功!"
     * }
     */
    public static class YsTokenResponse{
        private String code;
        private String msg;
        private JSONObject data;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMsg() {
            return msg;
        }

        public void setMsg(String msg) {
            this.msg = msg;
        }

        public JSONObject getData() {
            return data;
        }

        public void setData(JSONObject data) {
            this.data = data;
        }
    }
}
